package com.example.excelimporter.service;

import com.example.excelimporter.model.ImportStatistics;
import com.example.excelimporter.model.TemplateConfig;
import com.example.excelimporter.repository.ImportStatisticsRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DefaultPostImportProcessor implements PostImportProcessor {

    @Autowired
    private ImportStatisticsRepository statisticsRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void processAfterImport(TemplateConfig templateConfig, List<Object> validData, String targetTable) {
        // 1. 计算统计数据
        Map<String, Object> statistics = calculateStatistics(validData, targetTable);
        
        // 2. 更新相关配置
        Map<String, Object> configUpdates = updateRelatedConfigs(templateConfig, validData);
        
        // 3. 触发后续处理
        Map<String, Object> processingResults = triggerPostProcessing(templateConfig, validData);
        
        // 4. 保存统计结果
        saveStatistics(templateConfig, targetTable, validData.size(), statistics, configUpdates, processingResults);
    }

    private Map<String, Object> calculateStatistics(List<Object> validData, String targetTable) {
        Map<String, Object> statistics = new HashMap<>();
        
        // 基本统计信息
        statistics.put("totalRecords", validData.size());
        
        // 如果数据是数值类型，计算统计值
        if (!validData.isEmpty() && validData.get(0) instanceof Number) {
            List<Number> numbers = validData.stream()
                    .map(obj -> (Number) obj)
                    .collect(Collectors.toList());
            
            double sum = numbers.stream().mapToDouble(Number::doubleValue).sum();
            double average = sum / numbers.size();
            double max = numbers.stream().mapToDouble(Number::doubleValue).max().orElse(0);
            double min = numbers.stream().mapToDouble(Number::doubleValue).min().orElse(0);
            
            statistics.put("sum", sum);
            statistics.put("average", average);
            statistics.put("max", max);
            statistics.put("min", min);
        }
        
        return statistics;
    }

    private Map<String, Object> updateRelatedConfigs(TemplateConfig templateConfig, List<Object> validData) {
        Map<String, Object> configUpdates = new HashMap<>();
        
        // 更新模板配置信息
        configUpdates.put("lastImportTime", new Date());
        configUpdates.put("lastImportCount", validData.size());
        
        // 如果有字段配置，更新字段统计信息
        if (templateConfig.getFieldConfigs() != null) {
            Map<String, Object> fieldStats = new HashMap<>();
            templateConfig.getFieldConfigs().forEach(field -> {
                Map<String, Object> fieldInfo = new HashMap<>();
                fieldInfo.put("totalCount", validData.size());
                fieldInfo.put("lastUpdated", new Date());
                fieldStats.put(field.getFieldName(), fieldInfo);
            });
            configUpdates.put("fieldStatistics", fieldStats);
        }
        
        return configUpdates;
    }

    private Map<String, Object> triggerPostProcessing(TemplateConfig templateConfig, List<Object> validData) {
        Map<String, Object> processingResults = new HashMap<>();
        
        // 记录处理状态
        processingResults.put("status", "completed");
        processingResults.put("processedAt", new Date());
        
        // 如果有特定处理逻辑，可以在这里添加
        if (templateConfig.getDescription() != null && templateConfig.getDescription().contains("special")) {
            processingResults.put("specialProcessing", "executed");
        }
        
        return processingResults;
    }

    private void saveStatistics(TemplateConfig templateConfig, String targetTable, 
                              int totalRecords, Map<String, Object> statistics,
                              Map<String, Object> configUpdates, Map<String, Object> processingResults) {
        ImportStatistics importStatistics = new ImportStatistics();
        importStatistics.setTemplateId(templateConfig.getId());
        importStatistics.setTargetTable(targetTable);
        importStatistics.setTotalRecords(totalRecords);
        
        try {
            // 将统计结果转换为JSON
            importStatistics.setStatistics(objectMapper.writeValueAsString(statistics));
            
            Map<String, Object> combinedResults = new HashMap<>();
            combinedResults.put("configUpdates", configUpdates);
            combinedResults.put("processingResults", processingResults);
            importStatistics.setProcessingResults(objectMapper.writeValueAsString(combinedResults));
        } catch (JsonProcessingException e) {
            // 处理JSON转换异常
            importStatistics.setStatistics("{}");
            importStatistics.setProcessingResults("{\"error\": \"Failed to process statistics\"}");
        }
        
        // 保存到数据库
        statisticsRepository.save(importStatistics);
    }
} 